package com.citcc.api.task;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.citcc.api.netty.bean.ConsuMessage;
import com.citcc.api.netty.server.ChannelMap;
import com.citcc.api.netty.server.TerminalAddressMap;
import com.citcc.api.netty.xc.xcserver.XcServerToClient;

/**
 * @author liyachong
 * 2019年6月4日
 * 
 */
//@Component
public class TimeTask {
	
	private Logger log = LoggerFactory.getLogger(XcServerToClient.class);
	
	//定时任务处理对时
    //@Scheduled(cron = "0 0 5 * * ?")
    @Scheduled(fixedRate = 3 * 60 * 1000)//3分钟  测试
    public void checkTime() {
    	if(TerminalAddressMap.terminalAddressMap!=null){
    		for(Map.Entry<String,String> mapEntry : TerminalAddressMap.terminalAddressMap.entrySet()){
    			String key = mapEntry.getKey();
    			String terminalNo = mapEntry.getValue();
    			log.info("xc当前登录成功的协成设备信息-设备地址:"+key+"-->终端号:"+terminalNo);	
    		    //获取该终端号的通道
    		    Channel channel = ChannelMap.getChannelByName(terminalNo);
    		    if(channel!=null && channel.isConnected() && channel.isOpen()){
    		    	log.info("xc当前登录成功的协成设备信息-设备地址:"+key+"-->终端号:"+terminalNo+"-->链接状态:成功"+"-->开启状态:成功");	
    		    	ConsuMessage msg = new ConsuMessage();
    		    	xcRequestTime(terminalNo,msg,channel);
    		    }
    		    
    		}
    	}
    	
    }
    
    //封装对时数据体
    public void xcRequestTime(String terminalNo,ConsuMessage msg, Channel channel) {
        ChannelBuffer bodyBuffer = ChannelBuffers.buffer(15);
        bodyBuffer.writeShort(0x000D);//帧长度
        bodyBuffer.writeShort(0xFFF2);//帧长度取反
        bodyBuffer.writeByte(msg.getNo());//序列号 0x00
        bodyBuffer.writeByte(0x00);//数据对象
        bodyBuffer.writeByte(0x76);//请求对时命令
        //TODO 时间处理
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        int millisecond = cal.get(Calendar.MILLISECOND);
        bodyBuffer.writeShort(millisecond);
        bodyBuffer.writeByte(second);
        bodyBuffer.writeByte(minute);
        bodyBuffer.writeByte(hour);
        bodyBuffer.writeByte(day);
        bodyBuffer.writeByte(month);
        bodyBuffer.writeByte(year-2000);
        msg.setMsgBody(bodyBuffer);
        channel.write(msg);
        log.info("xc终端号请求对时:"+terminalNo+"-->时间报文:"+(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second+":"+millisecond));
    }
	
}
